Telegram Group & Telegram Channel
🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.



tg-me.com/pro_python_code/1804
Create:
Last Update:

🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.

BY Python RU


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pro_python_code/1804

View MORE
Open in Telegram


Python RU Telegram | DID YOU KNOW?

Date: |

The SSE was the first modern stock exchange to open in China, with trading commencing in 1990. It has now grown to become the largest stock exchange in Asia and the third-largest in the world by market capitalization, which stood at RMB 50.6 trillion (US$7.8 trillion) as of September 2021. Stocks (both A-shares and B-shares), bonds, funds, and derivatives are traded on the exchange. The SEE has two trading boards, the Main Board and the Science and Technology Innovation Board, the latter more commonly known as the STAR Market. The Main Board mainly hosts large, well-established Chinese companies and lists both A-shares and B-shares.

Telegram and Signal Havens for Right-Wing Extremists

Since the violent storming of Capitol Hill and subsequent ban of former U.S. President Donald Trump from Facebook and Twitter, the removal of Parler from Amazon’s servers, and the de-platforming of incendiary right-wing content, messaging services Telegram and Signal have seen a deluge of new users. In January alone, Telegram reported 90 million new accounts. Its founder, Pavel Durov, described this as “the largest digital migration in human history.” Signal reportedly doubled its user base to 40 million people and became the most downloaded app in 70 countries. The two services rely on encryption to protect the privacy of user communication, which has made them popular with protesters seeking to conceal their identities against repressive governments in places like Belarus, Hong Kong, and Iran. But the same encryption technology has also made them a favored communication tool for criminals and terrorist groups, including al Qaeda and the Islamic State.

Python RU from in


Telegram Python RU
FROM USA